import 'dart:convert';

import 'package:collection/collection.dart';
import 'package:distribution_mall_flutter/constant/cf_constant.dart';
import 'package:distribution_mall_flutter/entity/pay/list/pay_list_entity.dart';
import 'package:distribution_mall_flutter/generated/l10n.dart';
import 'package:distribution_mall_flutter/pages/goods/checkout/checkout_provider.dart';
import 'package:distribution_mall_flutter/pages/pay/pay_list/pay_list_provider.dart';
import 'package:distribution_mall_flutter/provider/common/pay.dart';
import 'package:distribution_mall_flutter/provider/order/order.dart';
import 'package:distribution_mall_flutter/utils/collection.dart';
import 'package:distribution_mall_flutter/utils/debug.dart';
import 'package:distribution_mall_flutter/widgets/cache_memoryImage_provider.dart';
import 'package:distribution_mall_flutter/widgets/modal_button.dart';
import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:getwidget/components/radio_list_tile/gf_radio_list_tile.dart';

class EPModalPay extends ConsumerStatefulWidget {
  final Function(PayMethodInfo? arg) footerCallback;
  final PayMethodInfo? initPayInfo;

  const EPModalPay({super.key, required this.footerCallback, this.initPayInfo});

  @override
  ConsumerState<ConsumerStatefulWidget> createState() => _EPModalPay();
}

class _EPModalPay extends ConsumerState<EPModalPay> {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      if (widget.initPayInfo != null) {
        ref
            .read(selectPayMethodProvider.notifier)
            .setPayMethodInfo(widget.initPayInfo);
      } else {
        var types = ref
            .read(checkOutResultProvider)?.paymentMethodList
            ?.types ??
            [];
        var onlyOneCanUsePayMethod = types.onlyOneCanUsePayMethod();
        if (onlyOneCanUsePayMethod != null) {
          ref.read(selectPayMethodProvider.notifier).setPayMethodInfo(
              onlyOneCanUsePayMethod);
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    var paymentMethodList = ref.watch(checkOutResultProvider)?.paymentMethodList;
    return Material(
        child: EPModalButton(
          title: S.current.payment_method,
          onFooterPressed: () {
            widget.footerCallback(ref.read(selectPayMethodProvider));
          },
          footerMargin:
          const EdgeInsets.symmetric(horizontal: EdgeConstant.edge218),
          hasDefaultFooter: true,
          maxHeightScale: 0.8,
          buttonText: S.current.confirm,
          padding: const EdgeInsets.fromLTRB(0, 23.7, 0, 0),
          children: [PayListItem(paymentMethodList: paymentMethodList?.types)],
        ));
  }
}

class PayListItem extends ConsumerWidget {
  final Function(PaymentMethod arg)? callBack;
  final List<PayListType>? paymentMethodList;

  const PayListItem({super.key, this.callBack, this.paymentMethodList});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final payListExpandedList = ref.watch(payListExpandedListProvider);

    ///已选择的地址
    final selectPayMethod = ref.watch(selectPayMethodProvider);

    ///如果已经传递过来就不获取了
    var payList =
        (paymentMethodList ?? ref.watch(payListProvider))?.formatPayList ?? [];
    var allCanUsePayMethod =
    CollectionUtils.mergeList(payList.map((e) => e.children))
        .where((e) => e.displayable == true && e.isUsable == true);

    ///判断是否只有一个支付方式
    bool isOnlySinglePayMethod = allCanUsePayMethod.length == 1;
    if (isOnlySinglePayMethod) {
      return buildGfRadioListTile(
          allCanUsePayMethod.first,
          ref,
          payList
              .firstWhere((e) => e.children.contains(allCanUsePayMethod.first)),
          selectPayMethod);
    }
    return ExpansionPanelList(
        expansionCallback: (panelIndex, isExpanded) {
          ref
              .read(payListExpandedListProvider.notifier)
              .triggerExpanded(payList, panelIndex, isExpanded);
        },
        dividerColor: ColorConstant.grey233_4,
        elevation: 0,
        expandedHeaderPadding: EdgeInsets.zero,
        expandIconColor: const Color.fromRGBO(162, 162, 162, 1),
        children: payList
            .where((FormatType type) => type.typeDisplayable == true)
            .mapIndexed((index, type) {
          return ExpansionPanel(
              backgroundColor: Colors.white,
              isExpanded: payListExpandedList.isEmpty
                  ? false
                  : payListExpandedList[index],
              canTapOnHeader: true,
              headerBuilder: (_, isExpanded) =>
                  Container(
                    padding: const EdgeInsets.only(left: EdgeConstant.edge218),
                    alignment: Alignment.centerLeft,
                    child: Text(
                      type.typeDisplay ?? '',
                      style: const TextStyle(
                          fontSize: FontConstant.f146,
                          fontWeight: FontWeight.bold,
                          color: Colors.black,
                          letterSpacing: TextConstant.letterSpacing),
                    ),
                  ),
              body: Column(
                  children: type.children
                      .where((element) => element.displayable == true)
                      .map((paymentMethod) =>
                      Container(
                          constraints: const BoxConstraints(
                              minHeight: 60, maxHeight: 75),
                          alignment: Alignment.center,
                          child: Column(
                            children: [
                              const Expanded(child: SizedBox.shrink()),
                              buildGfRadioListTile(paymentMethod, ref, type,
                                  selectPayMethod),
                              const Expanded(child: SizedBox.shrink()),
                            ],
                          )))
                      .toList() ??
                      []));
        }).toList());
  }

  GFRadioListTile<String?> buildGfRadioListTile(PaymentMethod paymentMethod,
      WidgetRef ref, FormatType type, PayMethodInfo? selectPayMethod) {
    return GFRadioListTile(
        onChanged: paymentMethod.isUsable == true
            ? (value) {
          ref.read(selectPayMethodProvider.notifier).setPayMethodInfo(
              PayMethodInfo(
                  type: type,
                  paymentMethod: paymentMethod,
                  methodCode: value));
        }
            : null,
        value: paymentMethod.methodCode,
        groupValue: selectPayMethod?.methodCode,
        size: 19,
        margin: EdgeInsets.zero,
        padding: const EdgeInsets.symmetric(
            horizontal: EdgeConstant.edge218, vertical: EdgeConstant.edge5),
        radioColor: Colors.white,
        avatar: paymentMethod.icon != null
            ? paymentMethod.icon!.startsWith('http')
            ? ExtendedImage.network(
          paymentMethod.icon!,
          width: 20,
          height: 20,
        )
            : Image(
          image: CacheMemoryImageProvider(
              'paymentMethod_${paymentMethod.methodCode}',
              base64.decode(paymentMethod.icon!.split(',').last)),
          width: 20,
          height: 20,
        )
            : null,
        inactiveBorderColor: paymentMethod.isUsable == true
            ? Colors.black
            : ColorConstant.grey156,
        activeBgColor: ColorConstant.primaryColor,
        title: Text(
          paymentMethod.methodName ?? '',
          style: TextStyle(
              color: paymentMethod.isUsable == true
                  ? Colors.black87
                  : ColorConstant.grey156,
              fontSize: FontConstant.f146),
        ),
        subTitle: Text(
          paymentMethod.subTitle ?? '',
          style: TextStyle(
              color: paymentMethod.isUsable == true
                  ? Colors.black45
                  : ColorConstant.grey228,
              fontSize: FontConstant.f127),
        ));
  }
}
